package com.yyk.yiliao.ui.activity.detail.activity;


import android.graphics.drawable.Drawable;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseActivity;
import com.yyk.yiliao.adapter.CommonTabPagerAdapter;
import com.yyk.yiliao.ui.activity.detail.fragment.Detail_Fragment_One;
import com.yyk.yiliao.ui.activity.detail.fragment.Detail_Fragment_Three;
import com.yyk.yiliao.ui.activity.detail.fragment.Detail_Fragment_Two;
import com.yyk.yiliao.ui.activity.shopcart.ShopCart_Activity;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.widget.paowuxian.BazierAnimView;
import com.yyk.yiliao.util.ToastUtil;
import com.yyk.yiliao.ui.login.activity.LogIn_Activity;
import com.yyk.yiliao.util.ebs.MessageEvent;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.util.rx.RxUtils;
import com.yyk.yiliao.bean.CartAddcart;
import com.yyk.yiliao.bean.StoreGoodsinfo_Info;
import com.yyk.yiliao.widget.ViewPagerScroller;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * 商品详情  购物 的详情界面，  里面有
 * 1.商品 预览
 * 2.商品 详情
 * 3.商品 评论
 */

public class Detail_Activity extends BaseActivity {
    @BindView(R.id.mDetail_gwc)
    LinearLayout mDetailGwc;
    @BindView(R.id.tablelayout)
    TabLayout tablelayout;
    @BindView(R.id.vp)
    ViewPager vp;
    @BindView(R.id.mDetail_add)
    RelativeLayout mDetailAdd;
    @BindView(R.id.mDetail_buy)
    RelativeLayout mDetailBuy;
    @BindView(R.id.ll_bottom_cfy)
    LinearLayout llBottomCfy;
    @BindView(R.id.toolbar) //自定义Toolbar
            Toolbar toolbar;
    @BindView(R.id.mDetail_bottom)
    LinearLayout mDetailBottom;

    @BindView(R.id.ceshi) //分享
            TextView ceshi;

    //抛物线
    @BindView(R.id.cornerimg) //购物车图标
            ImageView cornerImg;
    @BindView(R.id.bezier_anim) //抛物线
            BazierAnimView bazierAnimView;
    private Map<String, String> map;

    private int id; //商品ID

    private String pic; //抛物线图片


    private void setView() {
        initTablelayout();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        //        //3.取消注册事件
        EventBus.getDefault().unregister(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_detail;
    }

    @Override
    public void initView() {
        initToolbar();

    }

    /**
     * 因为中间是一个tabltyout ，嫌麻烦，就直接在布局中动态添加了一个 回退建， 效果是一样的，就是感觉有点瑕疵，不舒服
     */
    private void initToolbar() {
        hidetoolBar();
        final Drawable upArrow = getResources().getDrawable(R.mipmap.icon_shangp_fh);
        toolbar.setNavigationIcon(upArrow);
        //设置返回按钮的点击事件
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    @Override
    public void initData() {
        EventBus.getDefault().register(this);
        initGetIntent();
        setView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMoonEvent(MessageEvent messageEvent) {
//        id = Integer.parseInt(messageEvent.getMessage());
    }

    /**
     * 这个 bundle传值以后再搞把
     */
    private void initGetIntent() {
        /**
         * 获取 传过来的商品id
         */
        if (getBundle() != null) {
            id = getBundle().getInt("id");
        }
    }

    private void initTablelayout() {
        List<String> datas = new ArrayList<>();
        datas.add("商品");
        datas.add("详情");
        datas.add("评论");
        CommonTabPagerAdapter adapter = new CommonTabPagerAdapter(getSupportFragmentManager()
                , datas.size(), datas, this);
        //因为内部fragment 已经 是高级操作了，不能再复用所以分开了
        adapter.setListener(new CommonTabPagerAdapter.TabPagerListener() {
            @Override
            public Fragment getFragment(int position) {
                Bundle bundle = new Bundle();
                bundle.putInt("id", id);
                if (position == 0) {
                    Detail_Fragment_One one = Detail_Fragment_One.newInstance(position);
                    one.setArguments(bundle);
                    return one;
                } else if (position == 1) {
                    Detail_Fragment_Two two = Detail_Fragment_Two.newInstance(position);
                    two.setArguments(bundle);
                    return two;
                } else {
                    return Detail_Fragment_Three.newInstance(position);
                }
            }
        });
        ViewPagerScroller scroller = new ViewPagerScroller(this);
        scroller.setScrollDuration(1000);
        scroller.initViewPagerScroll(vp);
        vp.setAdapter(adapter);
        tablelayout.setupWithViewPager(vp);
    }


    @OnClick({R.id.mDetail_add, R.id.mDetail_buy, R.id.mDetail_gwc})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.mDetail_add:

    map = new TreeMap<>();

                map.put("uid", Hawk.get("uid", 0) + "");
                map.put("gid", id + "");
                map.put("num", "1");
                map.put("sign", Md5Util2.createSign(map));
                setBuyShop(map, false);
                break;
            case R.id.mDetail_buy:
                int uid = Hawk.get("uid", 0);
                Logger.i("账号id==" + uid);
                if (uid == 0) {
                    startAct(LogIn_Activity.class);
                } else {
                    Map<String, String> mDetail_gwc = new TreeMap<>();
                    mDetail_gwc.put("uid", Hawk.get("uid", 0) + "");
                    mDetail_gwc.put("gid", id + "");
                    mDetail_gwc.put("num", "1");
                    mDetail_gwc.put("sign", Md5Util2.createSign(mDetail_gwc));
                    setBuyShop(mDetail_gwc, true);
                    startAct(ShopCart_Activity.class);
                }

                break;
            case R.id.mDetail_gwc:
                int uid2 = Hawk.get("uid", 0);
                if (uid2 == 0) {
                    startAct(LogIn_Activity.class);
                } else {
                    startAct(ShopCart_Activity.class);
                }
                break;
        }
    }

    private void setBuyShop(Map<String, String> map, final boolean flag) {
        RxUtils.getInstance().retrofit.create(ApiService.class).postCartAddcart(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<CartAddcart>() {

                    @Override
                    public void onCompleted() {
                        //完成的时候调用
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(CartAddcart info) {
                        if (info.getCode() == 1) {
                            if (flag) {
                                startAct(ShopCart_Activity.class);
                            } else {
                                //加入购物车动画
                                bazierAnimView.startCartAnim(mDetailAdd, mDetailGwc, R.layout.l_move, pic);
                            }
                        } else if (info.getCode() == 101) {
                            ToastUtil.showShort(Detail_Activity.this, "没有该商品 ");
                        } else if (info.getCode() == 102) {
                            ToastUtil.showShort(Detail_Activity.this, "插入失败 ");
                        } else if (info.getCode() == 103) {
                            ToastUtil.showShort(Detail_Activity.this, "购物车已存在 ");
                        } else if (info.getCode() == 104) {
                            ToastUtil.showShort(Detail_Activity.this, "商品数量修改失败 ");
                        } else {
                            ToastUtil.showShort(Detail_Activity.this, "商品删除失败 ");
                        }
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        initShopOne();
    }

    /**
     * 商品内容
     */
    private void initShopOne() {
        Map<String, String> map = new TreeMap<>();

        map.put("page", 1 + "");
        map.put("id", id + "");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postStorGoodsinfo(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new Subscriber<StoreGoodsinfo_Info>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(StoreGoodsinfo_Info info) {
                        Logger.e("商品详情大页面" + info.toString());
                        if (info.getCode() == 1) {
                            //设置viewpager
                            List<StoreGoodsinfo_Info.DataBean.GoodsimgsBean> goodsimgs = info.getData().getGoodsimgs();
                            pic = goodsimgs.get(0).getImg();
                        }
                    }
                });


    }
}
